package com.aring.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.aring.bean.BattleInfo;
import com.aring.bean.MatchInfo;
import com.aring.bean.Page;
import com.aring.bean.Place;
import com.aring.bean.PlaceNumber;
import com.aring.bean.ReserveInfo;
import com.aring.bean.School;
import com.aring.bean.TimeTable;
import com.aring.bean.User;
import com.aring.service.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/register.do",method=RequestMethod.POST)
	public ModelAndView register(String account,String password,String password2,String school){
		ModelAndView mView = new ModelAndView("error");
		if(!password.equals(password2)){
			mView.addObject("message", "密码不一致");
			return mView;
		}
		
		try {
			User user = new User();
			user.setAccount(account);
			user.setPassword(password);
			user.setSchool(school);
			System.out.println(user.toString());
			userService.register(user);	
		} catch (Exception e) {
			e.printStackTrace();
			mView.addObject("message",e.getMessage());
			return mView;
		}
		
		mView.addObject("next","user/login.jsp");
		mView.addObject("message","注册成功");
		mView.setViewName("login");
		return mView;
	}
	
	
	/**
	 * 用户登录
	 * @param user
	 */
	@RequestMapping(value="/login.do",method=RequestMethod.POST)
	public ModelAndView login(User user,HttpServletResponse response,HttpServletRequest request){
		
		ModelAndView mView = new ModelAndView();
		try {
			user = userService.login(user);		
		} catch (RuntimeException e) {
			e.printStackTrace();
			mView.setViewName("error");
			mView.addObject("message",e.getMessage()); 
			return mView;
		}		
		Cookie cookie = new Cookie("uid",user.getId()+"");
		Cookie cookie2 = new Cookie("account",user.getAccount().trim());	
		response.addCookie(cookie);
		response.addCookie(cookie2);
		mView.setViewName("redirect:index.jsp");
		mView.addObject("user", user);		
		return mView;
	}
	
	@RequestMapping(value="getUserInfo.do", method=RequestMethod.GET)
	public ModelAndView geUserInfo(HttpServletRequest request,String page){
		ModelAndView mView = new ModelAndView("error");	
		User user = new User();
		if(checkLogin(request,user)){
			user = userService.getUserInfo(user);
			System.out.print(user);
			request.getSession().setAttribute("user",user);			
			mView.setViewName(page);
			return mView;
		}else {
			mView.addObject("message", "未登录");
			return mView;
		}
	}
	
    /**
     * 设置用户信息
     * @param user
     */
	@RequestMapping(value="user/setting.do",method=RequestMethod.POST)
	public ModelAndView settingInfo(User user,HttpServletRequest request){
		ModelAndView mView = new ModelAndView("error");	
		if(!checkLogin(request, user)){
			mView.addObject("message", "未登录");
			return mView;
		}
		
		if(user.getSchool()==null || user.getHobby()==null || user.getSex()==null){
			mView.addObject("message", "数据不合法");
			return mView;
		}
		
		System.out.println(user.toString());
		
		try {
			userService.settingInfo(user);			
		} catch (Exception e) {
			e.printStackTrace();
			mView.addObject("message", e.getMessage());
			return mView;
		}
		mView.addObject("user", userService.getUserInfo(user));
		mView.setViewName("user/info");
		return mView;
	}
	

	@RequestMapping(value="getSchoolInfo.do" , method=RequestMethod.GET)
	public String getSchoolInfo(HttpServletRequest request){
        List<School> schools = userService.getSchoolInfo();
		request.getSession().setAttribute("schools", schools);
		return "redirect:user/school.jsp";
	}
	
	
	@RequestMapping(value="publicGame.do",method=RequestMethod.POST)
	public ModelAndView publicGame(HttpServletRequest request,BattleInfo battleInfo){
		ModelAndView mView = new ModelAndView("error");	
		User user = new User();
		if(!checkLogin(request, user)){
			mView.addObject("message", "未登录");
			return mView;
		}
		else{			
			try {
				battleInfo.setPublicTime(new Date());
				battleInfo.setUserId(user.getId());
				System.out.println(battleInfo);
				userService.publicGame(battleInfo);
				mView.setViewName("redirect:index.jsp");
				return mView;
			} catch (Exception e) {
				e.printStackTrace();
				mView.addObject("message", e.getMessage());
				return mView;				
			}
		}
	}
	
	@RequestMapping(value="getBatteInfo.do" , method=RequestMethod.GET)
	public ModelAndView getBatteInfo(HttpServletRequest request,String pageName,int page){
		ModelAndView mView = new ModelAndView("error");
		if(page<=0) page =1;
		Page page2 = new Page();
		page2.setSize(10);
		page2.setNumber(page);
		page2.setPost(page2.getSize()*(page-1));
		page2.setPre(page2.getSize());
		System.out.println(page2);
		try {
		  List<BattleInfo> battleInfos = userService.getBattleInfoByPage(page2);
			  request.getSession().setAttribute("battleInfos", battleInfos);
			  mView.setViewName(pageName+"?page="+page);
			  return mView;
		} catch (Exception e) {
			e.printStackTrace();
			mView.addObject("message", e.getMessage());
			return mView;	
		}
		
		
	}
	
	
	@RequestMapping(value="getPlace.do",method=RequestMethod.GET)
	public ModelAndView getPlace(HttpServletRequest request,int schoolId,String pageName){
		ModelAndView mView = new ModelAndView("error");
		try {
			List<Place> places = userService.getPlaces(schoolId);
			request.getSession().setAttribute("places",places);
			mView.setViewName(pageName+"?schoolId="+schoolId);
			return mView;
		} catch (Exception e) {
			mView.addObject("message", e.getMessage());
			return mView;
		}
	}
	
	@RequestMapping(value="getPlaceNumber.do", method=RequestMethod.GET)
	public ModelAndView getPlaceNumber(HttpServletRequest request,int placeId,String pageName){
		ModelAndView mView = new ModelAndView("error");
		try {
			List<PlaceNumber> placeNumbers = userService.getPlaceNumbers(placeId);
			request.getSession().setAttribute("placeNumbers",placeNumbers);
			mView.setViewName(pageName+"?placeId="+placeId);
			return mView;
		} catch (Exception e) {
			mView.addObject("message", e.getMessage());
			return mView;
		}
	}
	
	
	@RequestMapping(value="getTimeTable.do", method=RequestMethod.GET)
	public ModelAndView  getTimeTable(HttpServletRequest request,int placeNumberId,String pageName,int placeId){
		ModelAndView mView = new ModelAndView("error");
		try {
			List<TimeTable> tables = userService.getTables(placeNumberId);
			request.getSession().setAttribute("tables", tables);
			mView.setViewName(pageName+"?placeId="+placeId+"&placeNumberId="+placeNumberId);
			return mView;			
		} catch (Exception e) {
			mView.addObject("message", e.getMessage());
			return mView;			
		}
	}
	
	
	@RequestMapping(value="reserve.do", method=RequestMethod.GET)
	public ModelAndView reserve(HttpServletRequest request,int tId,int placeId,int placeNumberId){
		ModelAndView mView = new ModelAndView("error");
		User user = new User();
		if(!checkLogin(request, user)){
			mView.addObject("message", "未登录");
			return mView;
		}
		else
			try {	
			ReserveInfo info = new ReserveInfo();
			info.setTime(new Date());
			info.setTimeTableId(tId);
			info.setUserId(user.getId());
			TimeTable table = new TimeTable();
			table.setId(tId);
			table.setStatus(1);		
			System.out.println(info);
			userService.reservePalce(info);
			userService.updateTimeTableStatus(table);		
			List<TimeTable> tables = userService.getTables(placeNumberId);
			request.getSession().setAttribute("tables", tables);
			mView.setViewName("redirect:/user/timeTable.jsp"+"?placeId="+placeId+"&placeNumberId="+placeNumberId);
			return mView;
		} catch (Exception e) {
			mView.addObject("message", e.getMessage());
			return mView;
		}
		
	}
	
	
	
	@RequestMapping(value="logout.do",method=RequestMethod.GET)
	public String logout(HttpServletRequest request,HttpServletResponse response){
		Cookie[] cookies = request.getCookies();
		if(cookies==null) return "index";
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = new Cookie(cookies[i].getName(), null);
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
		return "redirect:index.jsp";
	}
	
	@RequestMapping(value="getMatchInfo.do" , method=RequestMethod.GET)
	public ModelAndView getMatchInfo(HttpServletRequest request,int page,String pageName){
		ModelAndView mView = new ModelAndView("error");
		if(page<=0) page =1;
		Page page2 = new Page();
		page2.setSize(10);
		page2.setNumber(page);
		page2.setPost(page2.getSize()*(page-1));
		page2.setPre(page2.getSize());
		System.out.println(page2);
		try {
		  List<MatchInfo> matchInfos = userService.getMatchInfosByPage(page2);		  
			  request.getSession().setAttribute("matchInfos", matchInfos);
			  mView.setViewName(pageName+"?page="+page);
			  return mView;
		} catch (Exception e) {
			e.printStackTrace();
			mView.addObject("message", e.getMessage());
			return mView;	
		}
	}
	
	
	
	
	
	private boolean checkLogin(HttpServletRequest request,User user){
		Cookie cookie[] = request.getCookies();
		if(cookie==null) return false;
		for (int i = 0; i < cookie.length; i++) {
			if("uid".equals(cookie[i].getName())){
				user.setId(Integer.valueOf(cookie[i].getValue()));
				return true;
			}
		}
	 return false;
	}
	
}
